package org.aphelie.torg.ruler.internal.ui.editor.character.context;

import org.aphelie.torg.ruler.internal.ui.editor.character.text.XMLPartitionScanner;
import org.aphelie.torg.ruler.internal.ui.editor.character.text.XMLStringPartitionScanner;
import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.rules.FastPartitioner;

public class XMLDocumentSetupParticipant implements IDocumentSetupParticipant {
	
	public static final String XML_PARTITIONING = "_tgr_xml_partitioning"; //$NON-NLS-1$

	@Override
	public void setup(IDocument document) {
		IDocumentPartitioner partitioner = createDocumentPartitioner();
		if (partitioner != null) {
			partitioner.connect(document);
			if (document instanceof IDocumentExtension3) {
				IDocumentExtension3 de3 = (IDocumentExtension3) document;
				de3.setDocumentPartitioner(XML_PARTITIONING, partitioner);
				partitioner = new FastPartitioner(new XMLStringPartitionScanner(), XMLStringPartitionScanner.STRING_PARTITIONS);
				partitioner.connect(document);
				de3.setDocumentPartitioner(XMLStringPartitionScanner.XML_STRING, partitioner);
			} else {
				document.setDocumentPartitioner(partitioner);
			}
		}
	}

	private IDocumentPartitioner createDocumentPartitioner() {
		return new FastPartitioner(new XMLPartitionScanner(), XMLPartitionScanner.PARTITIONS);
	}

}
